/*
 * Copyright (C) 2010 EPRO
 */
package com.epro.dx.activity;

import java.net.MalformedURLException;
import java.net.URL;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import android.app.ActionBar.LayoutParams;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.net.http.SslError;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.AbsoluteSizeSpan;
import android.view.Display;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.RotateAnimation;
import android.webkit.SslErrorHandler;
import android.webkit.WebSettings;
import android.webkit.WebSettings.LayoutAlgorithm;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baifendian.mobile.BfdAgent;
import com.epro.dx.R;
import com.epro.dx.activity.order.OrderPlaceActivity;
import com.epro.dx.adapter.DetailProductImageAdapter;
import com.epro.dx.adapter.ProductDetailDescriptionViewPagerAdapter;
import com.epro.dx.fragment.ProductDetaiDescriptionFragment;
import com.epro.dx.listenner.CustomAsyncTaskListener;
import com.epro.dx.listenner.MyAsyncTaskListenner;
import com.epro.dx.listenner.OnLoginSuccessedListenner;
import com.epro.dx.listenner.OnScrollChangeListenner;
import com.epro.dx.task.BaseNeedReLoginTask;
import com.epro.dx.task.GetActiveInfoAsyncTask;
import com.epro.dx.task.GetCountryCodeTask;
import com.epro.dx.task.SalesLimitAsyncTask;
import com.epro.dx.util.ActivityUtil;
import com.epro.dx.util.AsyncTaskUtil;
import com.epro.dx.util.DpPxUtils;
import com.epro.dx.util.GlobalConfig;
import com.epro.dx.util.LoginUtilTask;
import com.epro.dx.widget.CustomDialog;
import com.epro.dx.widget.MyProductDetailContainer;
import com.epro.dx.widget.MyViewPager;
import com.epro.dx.widget.PagerSlidingTabStrip;
import com.epro.dx.widget.SlideDetailsLayout;
import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.HitBuilders.EventBuilder;
import com.google.android.gms.analytics.Tracker;
import com.google.android.gms.analytics.ecommerce.Product;
import com.google.android.gms.analytics.ecommerce.ProductAction;
import com.weipu.common.DXApplication;
import com.weipu.common.DXApplication.TrackerName;
import com.weipu.common.constants.Constant;
import com.weipu.common.constants.ServerConstant;
import com.weipu.common.constants.ServerConstant.ReturnCode.User;
import com.weipu.common.facade.ProductServiceProvider;
import com.weipu.common.facade.content.api.BrowsingHistoryService;
import com.weipu.common.facade.content.api.MyCartService;
import com.weipu.common.facade.exception.DxException;
import com.weipu.common.facade.factory.ProviderFactory;
import com.weipu.common.facade.model.ActiveModel;
import com.weipu.common.facade.model.Lines;
import com.weipu.common.facade.model.OrderProductModel;
import com.weipu.common.facade.model.OrderProductModel.SalesLimit;
import com.weipu.common.facade.model.PreviewOrderModel;
import com.weipu.common.facade.model.ProductModel;
import com.weipu.common.facade.model.ReviewlistModel;
import com.weipu.common.facade.model.SalesLimitModel;
import com.weipu.common.util.AlertToast;
import com.weipu.common.util.Logger;
import com.weipu.common.util.StringUtil;

import static android.R.attr.country;


/**
 * 商品详情展示Activity 分三个部分，首先展示的是简介，还有详细说明，商品评论可点击顶部选项卡进行切换。
 *
 * @author cw55072
 * @version [1.0, 2010-08-30]
 */
@SuppressWarnings("ResourceType")
public class DetailActivity extends BaseFragmentActivity implements
        OnClickListener, DialogInterface.OnClickListener,
        OnScrollChangeListenner {
    private static final String TAG = DetailActivity.class.getSimpleName();

    /**
     * 评论小星
     */
    private RatingBar mIndicatorRatingBar;

    /**
     * 商品信息显示
     */
    private TextView tvProductName;

    private TextView detailPrice;

    // 商品市场价格
    private TextView detailOldPrice;

    private RelativeLayout llOldPrice;

    /**
     * 商品描述,规格
     */
    private TextView description;

    private ImageView farvitorBtn;

    private ImageView line;

    private TextView specifications;

    /**
     * 商品图片
     */
    private ViewPager viewPagerDetail;

    /**
     * 点点点
     */
    // private PageIndicator pageIndicator;

    private ProductServiceProvider productServiceProvider;

    private ProductModel newProductModel;

    /**
     * 评论返回数据列表
     */
    private ArrayList<ReviewlistModel> onePageReviewList = null;

    /**
     * 最多预留多少条浏览记录
     */
    private int showMax = 100;

    /**
     * 商品Id
     */
    private int productId = 0;

    /**
     * 返回参数
     */
    private String backAction = null;

    /**
     * 折扣
     */
    private LinearLayout llDiscount;

    private TextView tvDiscount;

    private LinearLayout detailReviews;

    private LinearLayout discriptionLayout;

    private TextView reviewsCount;

    private TextView reviewName;

    private TextView reviewCustomer;

    private TextView reviewDescription;

    private TextView seeMore;

    private TextView topbarRightCart;

    private LinearLayout topBarRightCartLayout;

    private boolean isHome = false;

    private LinearLayout cartLayout;

    private Tracker t;

    private FrameLayout iconLayout;

    private TextView productNum;

    private TextView imageSelectedNum;

    private LinearLayout imageNumLayout;

    private int screenWidth;

    private DecimalFormat df = new DecimalFormat("0.00");

    private ImageView ivSoldout;

    private ArrayList<String> tabs = new ArrayList<String>();

    private ArrayList<ProductDetaiDescriptionFragment> descriptionFragments = new ArrayList<ProductDetaiDescriptionFragment>();

    private TextView descriptionKeepPushText;

    private MyProductDetailContainer container;

    private SlideDetailsLayout mSlideDetailsLayout;

    private WebView decriptionWebView;

    private WebView specificationWebView;

    private Button decriptionBtn;

    private Button specificationBtn;

    private TextView tagMVP;

    private TextView freeshippingBtn;

    private LinearLayout freeshippingForUpsBtn;
    private View hintDialog;
    private boolean isUS;
    private CustomDialog customDialog;
    private boolean isUSIp;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        t = DXApplication.getContext().getTracker(TrackerName.APP_TRACKER);
        eventBuilder = new HitBuilders.EventBuilder();
        // 不显示标题
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_product_detail);

        setTitleContent(R.string.title_details).setFocusable(false);
        screenWidth = getScreenWidth();
        initView();
        setListenner();
        intentFrom = getIntent();
        if (null != intentFrom) {
            Bundle data = intentFrom.getExtras();
            if (null != data) {
                backAction = data
                        .getString(ServerConstant.Parameter.PARAMETER_NAME_BACK_ACTION);
                productId = data
                        .getInt(ServerConstant.Parameter.PARAMETER_NAME_PRODUCT_ID);
                Logger.i(TAG, "productId " + productId);
                if (productId <= 0) {
                    finish();
                }
            }

            isFromMessage = intentFrom.getBooleanExtra("IsFromMessage", false);
            needCheckValid = intentFrom.getBooleanExtra("needCheckValid", false);
            noticeID = intentFrom.getStringExtra("NoticeID");
        }
        if (ActivityUtil.isLogin(this)) {
            String userName = StringUtil.getConfig(this,
                    ServerConstant.Parameter.PARAMETER_NAME_USER_ACCOUNT);
            if (null != userName
                    && userName.equals(StringUtil.getConfig(this, productId
                    + ""))) {
                farvitorBtn.setImageResource(R.drawable.like_orange);
            }
        }

        productServiceProvider = ProviderFactory.createProductProvider();
        queryCartCount();
        if (needCheckValid) {
            //需要校验活动的有效性
            MyAsyncTaskListenner myAsyncTaskListenner = new MyAsyncTaskListenner() {

                @Override
                public void onPreTask() {
                    showLoadingLayout(null);
                }

                @Override
                public void onPostTask(String result, Object obj) {
                    hideAllLayout();
                    if ("0".equals(result) && null != obj) {
                        ActiveModel model = (ActiveModel) obj;
                        if (model.getState() == ActiveModel.STATE_OFFLINE || model.getState() == ActiveModel.STATE_STOP) {
                            //活动下线
                            invalidActiveLayout.setVisibility(View.VISIBLE);
                            return;
                        }
                    }
                    AsyncTaskUtil.executeTask(new ProductDetailAsyncTask());
                }
            };
            GetActiveInfoAsyncTask getActiveInfoAsyncTask = new GetActiveInfoAsyncTask(3, noticeID, myAsyncTaskListenner);
            AsyncTaskUtil.executeTask(getActiveInfoAsyncTask);
        } else {
            AsyncTaskUtil.executeTask(new ProductDetailAsyncTask());
        }
    }


    private void checkUSSKU() {
        hintDialog = LayoutInflater.from(this).inflate(R.layout.dialog_common_hint,null);
        ((TextView) hintDialog.findViewById(R.id.dialog_common_content)).setText(getResources().getString(R.string.not_us_ip));
        hintDialog.findViewById(R.id.dialog_common_exit).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (customDialog.isShowing()) {
                    customDialog.dismiss();
                }
            }
        });
        customDialog = new CustomDialog(this, 0, 0, hintDialog, R.style.DialogTheme);
        customDialog.show();
    }

    @Override
    protected void onResume() {
        super.onResume();
        // 发送当前浏览的屏幕名称
        t.setScreenName("ProductDetail");
        t.send(new HitBuilders.ScreenViewBuilder().build());
        // 发送事件记录当前的sku信息
        eventBuilder.setCategory("SKU").setAction("sku= " + productId);
        t.send(eventBuilder.build());
        // 百分点推荐
        BfdAgent.setDebugMode(Constant.BFD_DEBUGMODEL);
        BfdAgent.onResume(this);
        BfdAgent.onVisit(this, productId + "");
    }

    @Override
    protected void onPause() {
        super.onPause();
        t.setScreenName(null);
        BfdAgent.onPause(this);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        Logger.d(TAG, "onNewIntent");
        if (null != intent) {
            productId = intent.getExtras().getInt(
                    ServerConstant.Parameter.PARAMETER_NAME_PRODUCT_ID);
        }
        // new ProductDetailAsyncTask().execute();
        AsyncTaskUtil.executeTask(new ProductDetailAsyncTask());
        // new
        // ProductDetailAsyncTask().executeOnExecutor(ThreadUtil.getInstance().getThreadPoolIntance());
        super.onNewIntent(intent);
    }

    /**
     * 获取屏幕宽度
     *
     * @return
     */
    private int getScreenWidth() {
        WindowManager windowManager = getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        int screenWidth = display.getWidth();
        return screenWidth;
    }

    private void setListenner() {
        // setRightBtnBitmap().setOnClickListener(this);
        topBarRightCartLayout.setOnClickListener(this);
        seeMore.setOnClickListener(this);
        findViewById(R.id.ll_reviews_all).setOnClickListener(this);
        addToCartBtn = (TextView) findViewById(R.id.layout_btn_add_to_cart);

        addToCartBtn.setOnClickListener(this);
        buyNowBtn = (TextView) findViewById(R.id.buy_now_btn);

        buyNowBtn.setOnClickListener(this);
        soldOutBtn = (Button) findViewById(R.id.layout_btn_sold_out);
        buyNowAddLayout = (LinearLayout) findViewById(R.id.layout_add_buy);
        farvitorBtn.setOnClickListener(this);
        viewPagerDetail.setOnPageChangeListener(new OnPageChangeListener() {

            @Override
            public void onPageSelected(int position) {
                if (newProductModel != null) {
                    String[] images = newProductModel.getBigPictureURL();
                    if (null != images) {
                        productNum.setText(images.length + "");
                        imageSelectedNum.setText(position + 1 + "/");
                    }
                }
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {

            }

            @Override
            public void onPageScrollStateChanged(int arg0) {

            }
        });

        // 返回按钮的事件
        topbarLeftTv.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (isFromMessage) {
                    backToHome();
                } else {
                    finish();
                }
            }
        });

        decriptionBtn.setOnClickListener(this);
        specificationBtn.setOnClickListener(this);
    }

    private void setPriceStyle(TextView textView, String str,
                               int currencyCodeEndIndex) {
        SpannableStringBuilder spanBuilder = new SpannableStringBuilder(str);
        // style 为0 即是正常的，还有Typeface.BOLD(粗体) Typeface.ITALIC(斜体)等
        // size 为0 即采用原始的正常的 size大小
        int currencySize = getResources().getDimensionPixelSize(
                R.dimen.text_size_13);
        spanBuilder.setSpan(new AbsoluteSizeSpan(currencySize), 0,
                currencyCodeEndIndex, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        textView.setText(spanBuilder);
        // spanBuilder.setSpan(new TextAppearanceSpan(null, 0, 60, redColors,
        // null), 0, 3, Spanned.SPAN_EXCLUSIVE_INCLUSIVE); TextView tv_test =
        // (TextView) findViewById(R.id.tv_test); tv_test.setText(spanBuilder);
    }

    /**
     * 初始化视图
     */
    private void initView() {
        // setRightBtnContent(R.string.share).setOnClickListener(this);
        // container = (MyProductDetailContainer)
        // findViewById(R.id.detail_parent_container);
        // container.setScrollListenner(this);
        mSlideDetailsLayout = (SlideDetailsLayout) findViewById(R.id.slidedetails);
        decriptionBtn = (Button) findViewById(R.id.decription_btn);
        specificationBtn = (Button) findViewById(R.id.specification_btn);
        decriptionWebView = (WebView) findViewById(R.id.decription_wv);
        specificationWebView = (WebView) findViewById(R.id.specification_wv);
        setLeftBtnContent(true, -1);
        iconLayout = (FrameLayout) findViewById(R.id.product_image_layout);
        productNum = (TextView) findViewById(R.id.product_img_num);
        imageSelectedNum = (TextView) findViewById(R.id.product_select_num);
        imageNumLayout = (LinearLayout) findViewById(R.id.product_imagenum_layout);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                LayoutParams.MATCH_PARENT, screenWidth);
        iconLayout.setLayoutParams(params);

        topbarRightCart = (TextView) findViewById(R.id.topbar_right_cart);
        topBarRightCartLayout = (LinearLayout) findViewById(R.id.topbar_right_cart_layout);
        topBarRightCartLayout.setVisibility(View.VISIBLE);
        cartLayout = (LinearLayout) findViewById(R.id.add_cart_layout);
        cartLayout.setVisibility(View.GONE);
        // 商品小图浏览
        viewPagerDetail = (ViewPager) findViewById(R.id.detail_viewpager);
        viewPagerDetail.setId(100);
        // pageIndicator = (PageIndicator) findViewById(R.id.detail_indicator);
        // 折扣
        llDiscount = (LinearLayout) findViewById(R.id.ll_discount);
        tvDiscount = (TextView) findViewById(R.id.tv_discount);
        // 商品消费信息
        tvProductName = (TextView) findViewById(R.id.productNameText);
        detailPrice = (TextView) findViewById(R.id.detail_price);
        detailOldPrice = (TextView) findViewById(R.id.detail_old_price);
        llOldPrice = (RelativeLayout) findViewById(R.id.ll_old_price);

        // 商品品论
        detailReviews = (LinearLayout) findViewById(R.id.detail_reviews);
        reviewsCount = (TextView) findViewById(R.id.detail_reviews_count);
        reviewName = (TextView) findViewById(R.id.review_name);
        mIndicatorRatingBar = (RatingBar) findViewById(R.id.review_rating);
        reviewCustomer = (TextView) findViewById(R.id.review_customer);
        reviewDescription = (TextView) findViewById(R.id.review_description);
        seeMore = (TextView) findViewById(R.id.detail_more);
        // 商品详细描述
        // pagerSlidingTabStrip = (PagerSlidingTabStrip)
        // findViewById(R.id.indicator_tab);
        // topPagerSlidingTabStrip = (PagerSlidingTabStrip)
        // findViewById(R.id.top_indicator_tab);
        // pagerSlidingTabStrip
        // .setOnPageChangeListener(new OnPageChangeListener() {
        //
        // @Override
        // public void onPageSelected(int arg0) {
        // Log.i("TTT", "pagerSlidingTabStrip: " + arg0);
        // }
        //
        // @Override
        // public void onPageScrolled(int arg0, float arg1, int arg2) {
        // }
        //
        // @Override
        // public void onPageScrollStateChanged(int state) {
        //
        // }
        // });
        // topPagerSlidingTabStrip
        // .setOnPageChangeListener(new OnPageChangeListener() {
        //
        // @Override
        // public void onPageSelected(int arg0) {
        // Log.i("TTT", "topPagerSlidingTabStrip: " + arg0);
        // pagerSlidingTabStrip.updateTabStyles();
        // // pagerSlidingTabStrip.scrollToChild(viewPager.getCurrentItem(),
        // // 0);
        // }
        //
        // @Override
        // public void onPageScrolled(int arg0, float arg1, int arg2) {
        // }
        //
        // @Override
        // public void onPageScrollStateChanged(int state) {
        // Log.i("TTT",
        // "topPagerSlidingTabStrip: "
        // + viewPager.getCurrentItem());
        // //由于点击事件在topPagerSlidingTabStrip上 所以 为了保证两个PagerSlidingTabStrip
        // //同步 需在topPagerSlidingTabStrip Page事件响应后处理pagerSlidingTabStrip事件
        // if (state == ViewPager.SCROLL_STATE_IDLE) {
        // pagerSlidingTabStrip
        // .setCurrentPosition(topPagerSlidingTabStrip
        // .getCurrentPosition());
        // pagerSlidingTabStrip
        // .setCurrentPositionOffset(topPagerSlidingTabStrip
        // .getCurrentPositionOffset());
        // pagerSlidingTabStrip.scrollToChild(
        // viewPager.getCurrentItem(), 0);
        // pagerSlidingTabStrip.invalidate();
        // }
        // }
        // });
        // viewPager = (MyViewPager) findViewById(R.id.viewpager);
        farvitorBtn = (ImageView) findViewById(R.id.btn_add_wishlist);
        line = (ImageView) findViewById(R.id.line);
        discriptionLayout = (LinearLayout) findViewById(R.id.detail_block);

        // soldout标签
        ivSoldout = (ImageView) findViewById(R.id.soldout_img_detail);
        tagMVP = (TextView) findViewById(R.id.detail_tag_mvp);
        // 继续拖动显示详情的提示语
        descriptionKeepPushText = (TextView) findViewById(R.id.product_detail_keeppush_text);
        invalidActiveLayout = (RelativeLayout) findViewById(R.id.layout_invalid_active);
        freeshippingBtn = (TextView) findViewById(R.id.detail_tag_freeshipping);
        freeshippingForUpsBtn = (LinearLayout) findViewById(R.id.detail_tag_ups);
    }

    private void startCartAnimation() {
        Animation shake = AnimationUtils.loadAnimation(DetailActivity.this,
                R.anim.cart_shake);
        // topBarRightCartLayout.setAnimation(shake);
        topBarRightCartLayout.startAnimation(shake);
    }

    // private void gotoNodataPage(String message)
    // {
    // Bundle datas = new Bundle();
    // //页面要展示的文字
    // datas.putString(Constant.NoDataConstant.NO_DATA_KEY, message);
    //
    // //如果是从订单详情界面过来的，则在错误界面需要回传传递orderNumber
    // if (ServerConstant.ActionConstant.ACTION_ORDER_DETAIL.equals(backAction))
    // {
    // datas.putString("orderNumber",
    // getIntent().getStringExtra("orderNumber"));
    // }
    // //要跳转的Action
    // datas.putString(Constant.NoDataConstant.NO_DATA_ACTION, backAction);
    // Intent in = new Intent(ServerConstant.ActionConstant.ACTION_NO_DATA);
    // in.putExtras(datas);
    // startActivity(in);
    // finish();
    // }

    /**
     * 给页面视图填充数据
     *
     * @param productModel
     */
    private void fillDataForView(ProductModel productModel) {
        if (null != productModel) {

            if (null != productModel.getBigPictureURL()) {
                processProductDetail(productModel.getBigPictureURL());
            }
            // 商品名称
            tvProductName.setText(productModel.getShortHeadLine1());

            // 商品价格
            String currencyCode = null;
            if (!TextUtils.isEmpty(productModel.getCurrencyCodeSymbol())) {
                currencyCode = productModel.getCurrencyCodeSymbol();
            } else {
                currencyCode = productModel.getCurrencyCode();
            }
            // detailPrice.setText(currencyCode+productModel.getPrice());
            float price = productModel.getPrice();
            setPriceStyle(detailPrice, currencyCode + df.format(price),
                    currencyCode.length());
            // 评论星星
            mIndicatorRatingBar.setRating(productModel.getProductRating());
            // 折扣
            double listPrice = productModel.getListprice();
            if ((listPrice - price) > 0) {
                llDiscount.setVisibility(View.VISIBLE);
                double discountPrice = ((listPrice - price) / listPrice) * 100;
                int discount = (int) discountPrice;
                double disDecimal = discountPrice - discount;
                // 主站逻辑 余数大于0.5时进一位
                if (disDecimal > 0.5) {
                    tvDiscount.setText(discount + 1 + "");
                } else {
                    tvDiscount.setText(discount + "");
                }
            }
            // if ((productModel.getListprice() - productModel.getPrice()) > 0)
            // {
            // llDiscount.setVisibility(View.VISIBLE);
            // int discount = (int) (((productModel.getListprice() -
            // productModel
            // .getPrice()) / productModel.getListprice()) * 100);
            // tvDiscount.setText(discount+"");
            // }

            // // 描述
            // description.setText(productModel.getIntroduction());
            //
            // // 规格
            // specifications.setText(productModel.getSpec());
            // 4.0产品描述
            initWebView(decriptionWebView, productModel.getIntroduction());
            initWebView(specificationWebView, productModel.getSpec());
            if (!TextUtils.isEmpty(productModel.getIntroduction())
                    || !TextUtils.isEmpty(productModel.getSpec())) {
                // if (!TextUtils.isEmpty(productModel.getIntroduction())) {
                // descriptionFragments
                // .add(new ProductDetaiDescriptionFragment(
                // productModel.getIntroduction()));
                // tabs.add(getString(R.string.product_detail_details));
                // }
                // if (!TextUtils.isEmpty(productModel.getSpec())) {
                // descriptionFragments
                // .add(new ProductDetaiDescriptionFragment(
                // productModel.getSpec()));
                // tabs.add(getString(R.string.product_detail_specifications));
                // }
                // viewPagerAdapter = new
                // ProductDetailDescriptionViewPagerAdapter(
                // getSupportFragmentManager(), descriptionFragments, tabs);
                // viewPager.setAdapter(viewPagerAdapter);
                // pagerSlidingTabStrip.setViewPager(viewPager);
                //
                // pagerSlidingTabStrip.setTextColor(
                // getResources()
                // .getColor(R.color.myorder_tab_text_normal),
                // getResources().getColor(
                // R.color.myorder_tab_text_selected));
                // topPagerSlidingTabStrip.setViewPager(viewPager);
                //
                // topPagerSlidingTabStrip.setTextColor(
                // getResources()
                // .getColor(R.color.myorder_tab_text_normal),
                // getResources().getColor(
                // R.color.myorder_tab_text_selected));
            } else {
                discriptionLayout.setVisibility(View.GONE);
                if (null != line) {
                    line.setVisibility(View.VISIBLE);
                }
            }

            if (productModel.getPrice() < productModel.getListprice()) {
                // detailOldPrice.setText(currencyCode+productModel.getListprice());
                float oldPrice = productModel.getListprice();
                setPriceStyle(detailOldPrice,
                        currencyCode + df.format(oldPrice),
                        currencyCode.length());
            } else {
                llOldPrice.setVisibility(View.GONE);
            }

            // 售完处理 hjd 无库存校验
            // if (productModel.getQuantity() <= 0)
            // {
            // findViewById(R.id.sold_out).setVisibility(View.VISIBLE);
            // }

            // app4.0 －－判断产品销售状态设置按钮显示
            if (productModel.getStatus() == 2 || productModel.getStatus() == 3) {
                // 空状态
                addToCartBtn.setVisibility(View.GONE);
                buyNowBtn.setVisibility(View.GONE);
                buyNowAddLayout.setVisibility(View.GONE);
                soldOutBtn.setVisibility(View.VISIBLE);
                ivSoldout.setVisibility(View.VISIBLE);
                // 产品sold out后隐藏折扣标签
                llDiscount.setVisibility(View.GONE);
            } else {
                // 正常状态
                addToCartBtn.setVisibility(View.VISIBLE);
                buyNowBtn.setVisibility(View.VISIBLE);
                buyNowAddLayout.setVisibility(View.VISIBLE);
                soldOutBtn.setVisibility(View.GONE);
                ivSoldout.setVisibility(View.GONE);
            }
            //app4.0 --判断是否是MVP显示标签
            int tag = productModel.getTag();
            if (tag == 1) {
                tagMVP.setVisibility(View.VISIBLE);
            } else {
                tagMVP.setVisibility(View.GONE);
            }
            // 判断是否大于15美元，显示Free Shopping
            if (productModel.isCanReturnSC()) {
                freeshippingBtn.setText(getString(R.string.product_freeship));
                freeshippingBtn.setCompoundDrawablesWithIntrinsicBounds(R.drawable.plane_green, 0, 0, 0);
            } else {
                freeshippingBtn.setText(getString(R.string.product_freeship_));
                freeshippingBtn.setCompoundDrawablesWithIntrinsicBounds(R.drawable.planeicon, 0, 0, 0);
            }

            freeshippingBtn.setVisibility(View.VISIBLE);

            //US仓版本修改 如果是US仓的SKU产品，展示free shipping需要修改图标和文案
            if (isUS){
                freeshippingForUpsBtn.setVisibility(View.VISIBLE);
                freeshippingBtn.setVisibility(View.GONE);
                tagMVP.setVisibility(View.GONE);
            }

        }
    }

    private void processProductDetail(String[] smallUrl) {
        int countOfList = smallUrl.length;
        // List<Fragment> fastSellingFragmentsLists = new ArrayList<Fragment>();
        imageNumLayout.setVisibility(View.VISIBLE);
        productNum.setText(countOfList + "");
        imageSelectedNum.setText("1/");

        viewPagerDetail.setAdapter(new DetailProductImageAdapter(this,
                smallUrl, screenWidth));
        viewPagerDetail.setCurrentItem(0);
        // for (int i = 0; i < countOfList; i++) {
        // fastSellingFragmentsLists.add(DetailsPromotionFragment.newInstants(
        // DetailActivity.this, smallUrl[i]));
        // }
        // if (null != fastSellingFragmentsLists
        // && !fastSellingFragmentsLists.isEmpty()) {
        // viewPagerDetail.setAdapter(new MyViewPagerAdapter(
        // getSupportFragmentManager(), fastSellingFragmentsLists,
        // isHome));
        // viewPagerDetail.setCurrentItem(0);
        // // pageIndicator.setViewPager(viewPagerDetail);
        // }
    }

    private boolean isActionCompleted = true;

    /**
     * 点击添加到收藏夹
     *
     * @return void [返回类型说明]
     * @throws throws [违例类型] [违例说明]
     * @see [类、类#方法、类#成员]
     */
    private void addWishList(View v) {
        if (!isActionCompleted) {
            return;
        }
        isActionCompleted = false;

        // 产品不存在
        if (null == newProductModel) {
            isActionCompleted = true;
            AlertToast.alert(DetailActivity.this, R.string.data_not_exist);
            return;
        }

        if (newProductModel.getSku() > 0) {
            // 如果未登录，则需要跳转到登录界面
            if (!ActivityUtil.isLogin(this)) {
                gotoLogin();
                isActionCompleted = true;
                return;
            }
            //
            AsyncTaskUtil.executeTask(new AddToWishListAsyncTask(
                    newProductModel.getSku(), ""));
            // new AddToWishListAsyncTask(newProductModel.getSku(),
            // "").execute();
        }
        // 产品无效
        else {
            isActionCompleted = true;
            AlertToast.alert(DetailActivity.this, R.string.invalid_data);
        }

    }

    private void gotoLogin() {
        Intent intent = new Intent(this, LoginActivity.class);
        Bundle data = new Bundle();
        // 设置返回参数,登录成功后需要返回到详情界面
        data.putString(ServerConstant.Parameter.PARAMETER_NAME_BACK_ACTION,
                ServerConstant.ActionConstant.ACTION_PRODUCT_DETAIL);
        data.putInt(ServerConstant.Parameter.PARAMETER_NAME_LOGIN_ACTION_TYPE,
                ServerConstant.Parameter.PARAMETER_ACTION_TYPE_PRODUCT_DETAIL);
        data.putInt(ServerConstant.Parameter.PARAMETER_NAME_PRODUCT_ID,
                productId);
        intent.putExtras(data);
        startActivity(intent);
    }

    /**
     * 监听按钮事件
     *
     * @param v
     */
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.topbar_right_tv:
                if (null == newProductModel) {
                    return;
                }
                new AlertDialog.Builder(DetailActivity.this)
                        .setTitle(getResources().getString(R.string.share))
                        .setPositiveButton(
                                getResources().getString(R.string.Shareto),
                                new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog,
                                                        int which) {
                                        Intent emailIntent = new Intent(
                                                android.content.Intent.ACTION_SEND);
                                        emailIntent.setType("text/html");
                                        emailIntent
                                                .putExtra(
                                                        android.content.Intent.EXTRA_SUBJECT,
                                                        R.string.desc);
                                        emailIntent
                                                .putExtra(
                                                        android.content.Intent.EXTRA_TEXT,
                                                        newProductModel
                                                                .getShortHeadLine1()
                                                                + "\n"
                                                                + "http://www.dealextreme.com/photogallery.dx/sku."
                                                                + newProductModel
                                                                .getSku()

                                                );

                                        startActivity(Intent.createChooser(
                                                emailIntent, "sendEmail......"));
                                    }
                                })
                        .setNegativeButton("Cancel",
                                new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog,
                                                        int which) {
                                        dialog.dismiss();
                                    }
                                }).create().show();
                break;
            case R.id.topbar_right_cart_layout:
                eventBuilder.setCategory("Click").setAction("Go to Cart");
                t.send(eventBuilder.build());
                Intent homeIntent = new Intent(this, HomeActivity.class);
                // 跳转购物车
                homeIntent.putExtra(HomeActivity.CURRENT_TAB_TAG,
                        getString(HomeActivity.titleArray[2]));
                startActivity(homeIntent);
                finish();
                break;
            case R.id.btn_add_wishlist:
                addWishList(v);
                break;
            case R.id.layout_btn_add_to_cart: {
                // 添加值购物车, hjd 无库存校验直接加入购物车
                // if (newProductModel.getQuantity() > 0)
                // {
                if (null == newProductModel) {
                    AlertToast.alert(DetailActivity.this, R.string.data_not_exist);
                    return;
                }
                if (newProductModel.getSku() > 0) {
                    addIntoMyCart(newProductModel);
                    // AlertToast.alert(DetailActivity.this,
                    // R.string.user_collection_add_success);
                } else {
                    AlertToast.alert(DetailActivity.this, R.string.invalid_data);
                }

                // }
                // else
                // {
                // btnPaynow.setFocusable(false);
                // btnMyCart.setFocusable(false);
                // AlertToast.alert(DetailActivity.this,
                // R.string.Item_is_temporarily_sold_out);
                // }
                break;
            }
            case R.id.buy_now_btn:
                if (null == newProductModel) {
                    AlertToast.alert(DetailActivity.this, R.string.data_not_exist);
                    return;
                }
                if (newProductModel.getSku() > 0) {
                    AsyncTaskUtil.executeTask(new CheckStock());
                } else {
                    AlertToast.alert(DetailActivity.this, R.string.invalid_data);
                }
                break;
            case R.id.detail_more:
                if (null == newProductModel) {
                    return;
                }
                Intent intentMore = new Intent(this, ReviewsActivity.class);
                Bundle dataMore = new Bundle();
                dataMore.putParcelable("detailModel", newProductModel);
                intentMore.putExtras(dataMore);
                startActivity(intentMore);
                break;
            case R.id.ll_reviews_all:
                if (null != onePageReviewList && onePageReviewList.size() != 0) {
                    Intent intent = new Intent(this, ReviewsDetailActivity.class);
                    Bundle data = new Bundle();
                    ReviewlistModel reviewModel = onePageReviewList.get(0);
                    if (null == reviewModel) {
                        return;
                    }
                    data.putSerializable("reviewModel", onePageReviewList.get(0));
                    intent.putExtras(data);
                    startActivity(intent);
                }
                break;
            case R.id.decription_btn:
                decriptionBtn
                        .setBackgroundResource(R.drawable.description_specifications_bg_on);
                specificationBtn
                        .setBackgroundResource(R.drawable.description_specifications_bg);
                decriptionBtn.setTextColor(getResources().getColor(
                        R.color.myorder_tab_text_selected));
                specificationBtn.setTextColor(getResources().getColor(
                        R.color.myorder_tab_text_normal));
                decriptionWebView.setVisibility(View.VISIBLE);
                specificationWebView.setVisibility(View.GONE);
                break;
            case R.id.specification_btn:
                specificationBtn
                        .setBackgroundResource(R.drawable.description_specifications_bg_on);
                decriptionBtn
                        .setBackgroundResource(R.drawable.description_specifications_bg);
                specificationBtn.setTextColor(getResources().getColor(
                        R.color.myorder_tab_text_selected));
                decriptionBtn.setTextColor(getResources().getColor(
                        R.color.myorder_tab_text_normal));
                specificationWebView.setVisibility(View.VISIBLE);
                decriptionWebView.setVisibility(View.GONE);
                break;
            default:
                break;
        }
    }

    @Override
    public void onClick(DialogInterface dialog, int which) {
        if (DialogInterface.BUTTON_POSITIVE == which) {
            String buyurl = Constant.BUYURL + newProductModel.getSku();
            // 调用浏览器进行使用URL
            Uri uri = Uri.parse(buyurl);
            Intent i = new Intent(Intent.ACTION_VIEW, uri);
            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(i);
        }
    }

    /**
     * 保存sku到本地数据库
     *
     * @param orderProductModel
     */
    private void saveSkuToLocalDB(OrderProductModel orderProductModel) {
        // 没有登陆，保存到本地购物车
        MyCartService myCartService = ProviderFactory
                .createMyCartServiceDBProvider();

        // OrderProductModel orderProductModel = new OrderProductModel();
        // orderProductModel.setSku(productmodels.getSku());
        // String[] smallPictureURL = productmodels.getSmallPictureURL();
        // if (null != smallPictureURL && smallPictureURL.length >= 1) {
        // orderProductModel.setSmallPictureURL(productmodels
        // .getSmallPictureURL()[0]);
        // }
        // orderProductModel.setPrice(productmodels.getPrice());
        // orderProductModel.setShortHeadLine1(productmodels.getShortHeadLine1());
        // orderProductModel.setFreeShipping(productmodels.getFreeShipping());
        // to set isFarvoite


        // 确保购物车互斥，851,852 以及主站正常sku（大于等于4位小于9位sku） ，三类商品不能任意组合在购物车，只能一类商品在购物车。
        // 先得到本地购物车里有的sku列表，看下是属于哪一类
        // 判断本地购物车里的类别与当前是否属于同一类

        // 否：弹出提示信息

        // 是：按原先的逻辑
        ArrayList<OrderProductModel> list = myCartService.getListByType(this, "1");
        if (list != null && !list.isEmpty()) {
            int sku = list.get(0).getSku();

            if (getSkuType(sku) != getSkuType(orderProductModel.getSku())) {
                AlertToast.alert(this, R.string.sku_add_conflict);
                return;
            }

        }

        OrderProductModel preOrderProductModel = myCartService.getBySku(
                DetailActivity.this, orderProductModel.getSku());

        // 无记录 --> 新增数据
        if (null == preOrderProductModel) {
            orderProductModel.setQuantity(1);
            myCartService.save(DetailActivity.this, orderProductModel);
        }
        // update
        else {
            orderProductModel.setId(preOrderProductModel.getId());
            // 更新订单数目加1
            orderProductModel
                    .setQuantity(preOrderProductModel.getQuantity() + 1);
            myCartService.update(DetailActivity.this, orderProductModel);
            Logger.i(
                    TAG,
                    "orderProductModel quantity: "
                            + orderProductModel.getQuantity());
        }
        AlertToast.alert(DetailActivity.this,
                R.string.user_collection_add_success);
        GlobalConfig.getInstance().setShoppingCartChange(true);
        queryCartCount();
        startCartAnimation();
    }

    /**
     * 得到当前sku类别
     *
     * @param sku
     * @return
     */
    private int getSkuType(int sku) {
        //经测试确认，需确保不互斥，如果需要互斥，请注释下面的if
        if (true) {
            return 0;
        }

        // 确保购物车互斥，851,852 以及主站正常sku（大于等于4位小于9位sku） ，三类商品不能任意组合在购物车，只能一类商品在购物车。
        String skuStr = String.valueOf(sku);
        if (skuStr.startsWith("851")) {
            return 1;
        } else if (skuStr.startsWith("852")) {
            return 2;
        } else if (skuStr.length() >= 4 && skuStr.length() < 9) {
            return 3;
        }
        return 0;
    }

    /**
     * 添加到购物车
     *
     * @param productmodels
     */
    private OrderProductModel addIntoMyCart(ProductModel productmodels) {

        OrderProductModel orderProductModel = new OrderProductModel();
        orderProductModel.setSku(productmodels.getSku());
        String[] smallPictureURL = productmodels.getSmallPictureURL();
        if (null != smallPictureURL && smallPictureURL.length >= 1) {
            orderProductModel.setSmallPictureURL(productmodels
                    .getSmallPictureURL()[0]);
        }
        String[] mediumPictureURL = productmodels.getMediumPictureURL();
        if (null != mediumPictureURL && mediumPictureURL.length >= 1) {
            orderProductModel.setMediumPictureURL(mediumPictureURL[0]);
        }
        orderProductModel.setPrice(productmodels.getPrice());
        orderProductModel.setShortHeadLine1(productmodels.getShortHeadLine1());
        orderProductModel.setFreeShipping(productmodels.getFreeShipping());
        final OrderProductModel saveProModel = orderProductModel;
        // 添加到百分点
        BfdAgent.onAddCart(this, productmodels.getSku() + "",
                productmodels.getPrice(), 1);

        if (!ActivityUtil.isLogin(this)) {
            final int sku = productmodels.getSku();
            ArrayList<Integer> skus = new ArrayList<Integer>();
            skus.add(sku);
            SalesLimitAsyncTask slAsyncTask = new SalesLimitAsyncTask(
                    new MyAsyncTaskListenner() {

                        @Override
                        public void onPreTask() {
                            showLoadingLayout(null);
                        }

                        @Override
                        public void onPostTask(String result, Object obj) {
                            hideAllLayout();
                            if ("0".equals(result)) {
                                Map<Integer, SalesLimitModel> tmpMap = (Map<Integer, SalesLimitModel>) obj;
                                if (null != tmpMap) {
                                    SalesLimitModel tmpLitmodel = tmpMap.get(sku);
                                    if (null != tmpLitmodel) {
                                        int limit = tmpLitmodel.getLimit();
                                        if (limit != -1 && limit < 1) {
                                            AlertToast.alert(
                                                    DetailActivity.this,
                                                    R.string.product_soldout);
                                        } else {
                                            saveSkuToLocalDB(saveProModel);
                                        }
                                    }
                                }
                            } else {
                                AlertToast.alert(DetailActivity.this,
                                        ServerConstant.ReturnCode.MESSAGEMAP
                                                .get(result));
                            }
                        }
                    }, skus);
            AsyncTaskUtil.executeTask(slAsyncTask);
        } else {
            // 已经登陆，添加到同步（在线）购物车，需要累计添加接口支持
            AsyncTaskUtil.executeTask(new Add2CartTask(productmodels.getSku(),
                    1, Long.parseLong(getCustomerID())));
        }
        measureAddToCart();
        return orderProductModel;
    }

    /**
     * @author Tony 描述：将商品添加到线上购物车的任务
     */
    class Add2CartTask extends AsyncTask<Void, Void, String> {

        private int sku;
        private int quantity;
        private long customerId;
        private PreviewOrderModel previewOrderModel;// 用于存储返回的购物车商品信息对象

        public Add2CartTask(int sku, int quantity, long customerId) {
            this.sku = sku;
            this.quantity = quantity;
            this.customerId = customerId;

        }

        @Override
        protected void onPreExecute() {
            // showWaitingDialog();
            showLoadingLayout(null);
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(Void... params) {
            try {
                // 覆盖式添加
                // count =
                // ProviderFactory.createShoppingCartServiceProvider().addCart(sku,
                // quantity, customerId);
                // 累加式添加
                previewOrderModel = ProviderFactory
                        .createShoppingCartServiceProvider().addCart(sku,
                                quantity, customerId,
                                ActivityUtil.getCustomerToken(), "");
            } catch (DxException e) {
                return e.getErrCode();
            }
            return "0";
        }

        @Override
        protected void onPostExecute(String result) {
            if ("0".equals(result)) {
                // hideWaitingDialog();
                hideAllLayout();
                if (previewOrderModel != null) {
//                    int count = previewOrderModel.getLines().size();
                    //遗留问题，如果getLines为空，会崩溃
                    if (previewOrderModel.getLines() == null) {
                        AlertToast.alert(DetailActivity.this,R.string.product_soldout);
                        return ;
                    }

                    int count = previewOrderModel.getLines() == null ? 0 : previewOrderModel.getLines().size();
                    if (0 < count) {
                        topBarRightCartLayout
                                .setBackgroundResource(R.drawable.nav_cart_new_black);
                    } else {
                        topBarRightCartLayout
                                .setBackgroundResource(R.drawable.nav_cart_no_black);
                    }
                    topbarRightCart.setText(count + "");
                    AlertToast.alert(DetailActivity.this,
                            R.string.user_collection_add_success);
                    startCartAnimation();
                }
            } else {
                if ("DMS100002".equals(result)) {
                    LoginUtilTask logintask = new LoginUtilTask(
                            new OnLoginSuccessedListenner() {

                                @Override
                                public void onLoginSuccesed() {
                                    AsyncTaskUtil.executeTask(new Add2CartTask(
                                            sku, 1, customerId));

                                }

                                @Override
                                public void onLoginFailed() {
                                    hideAllLayout();
                                    Intent intent = new Intent(
                                            DetailActivity.this,
                                            LoginActivity.class);
                                    intent.putExtra(
                                            ServerConstant.Parameter.PARAMETER_NAME_LOGIN_ACTION_TYPE,
                                            ServerConstant.Parameter.PARAMETER_ACTION_TYPE_AUTO_LOGIN_FAIL);
                                    DetailActivity.this.startActivity(intent);
                                }
                            }, DetailActivity.this, true);
                    AsyncTaskUtil.executeTask(logintask);
                } else if ("DMS100005".equals(result)) {
                    hideAllLayout();
                    AlertToast.alert(DetailActivity.this,
                            R.string.product_soldout);
                }/*
                 * else{ hideWaitingDialog();
				 * AlertToast.alert(DetailActivity.this,
				 * R.string.user_collection_add_failed); }
				 */ else {
                    AlertToast.alert(DetailActivity.this,
                            ServerConstant.ReturnCode.MESSAGEMAP.get(result));
                    // hideWaitingDialog();
                    hideAllLayout();
                }
            }
            super.onPostExecute(result);
        }

    }

    /**
     * 将信息添加到浏览记录
     *
     * @param productModel2
     */
    private void insertToNativeBrowseList(ProductModel productModel2) {
        // 接口
        BrowsingHistoryService browsingHistoryService = ProviderFactory
                .createBrowsingHistoryServiceDBProvider();
        // 客户端本地数据库中浏览记录对象列表
        ArrayList<OrderProductModel> nativeBrowseList = browsingHistoryService
                .selectMenusList(DetailActivity.this, "_id desc");

        // 如果本地浏览过的商品超过最大显示数时，先删除最前面的一条，然后再添加
        if (nativeBrowseList.size() >= showMax) {
            browsingHistoryService.deleteById(DetailActivity.this,
                    nativeBrowseList.get(nativeBrowseList.size() - 1).getId());
        }

        OrderProductModel browseHistory = new OrderProductModel();
        browseHistory.setSku(productModel2.getSku());

        // 根据id查询数据库是否已经存在
        ArrayList<OrderProductModel> list = browsingHistoryService
                .getBySelection(DetailActivity.this, "sku=?",
                        new String[]{browseHistory.getSku() + ""});

        // 如果不存在就加入到记录列表中
        if (null == list || list.isEmpty()) {
            browseHistory.setSku(productModel2.getSku());
            browseHistory.setShortHeadLine1(productModel2.getShortHeadLine1());
            String[] smallPictureURL = productModel2.getSmallPictureURL();
            if (null != smallPictureURL && smallPictureURL.length >= 1) {
                browseHistory.setSmallPictureURL(smallPictureURL[0]);
            }
            String[] mediumPictureURL = productModel2.getMediumPictureURL();
            if (null != mediumPictureURL && mediumPictureURL.length >= 1) {
                browseHistory.setMediumPictureURL(mediumPictureURL[0]);
            }
            browseHistory.setPrice(productModel2.getPrice());
            browseHistory.setFreeShipping(productModel2.getFreeShipping());
            browseHistory.setReviewCount(productModel2.getReviewCount());
            browseHistory.setProductRating(productModel2.getProductRating());
            // browseHistory.setProductSalelimit(productModel2.getQuantity() +
            // "");
            browsingHistoryService.save(DetailActivity.this, browseHistory);// 保存到数据库
        } else {
            // 如果存在 先删除再加入到记录列表
            browsingHistoryService.deleteTemplateBySelection(this, "sku=?",
                    new String[]{browseHistory.getSku() + ""});

            browseHistory.setSku(productModel2.getSku());
            browseHistory.setShortHeadLine1(productModel2.getShortHeadLine1());
            String[] smallPictureURL = productModel2.getSmallPictureURL();
            if (null != smallPictureURL && smallPictureURL.length >= 1) {
                browseHistory.setSmallPictureURL(smallPictureURL[0]);
            }
            browseHistory.setPrice(productModel2.getPrice());
            browseHistory.setFreeShipping(productModel2.getFreeShipping());
            browseHistory.setReviewCount(productModel2.getReviewCount());
            browseHistory.setProductRating(productModel2.getProductRating());
            // browseHistory.setProductSalelimit(productModel2.getQuantity() +
            // "");
            browsingHistoryService.save(DetailActivity.this, browseHistory);// 保存到数据库
        }

    }

    /**
     * 加载商品详情任务
     *
     * @author hjd008
     * @version [版本号, 2014-12-23]
     * @see [相关类/方法]
     * @since [产品/模块版本]
     */
    protected class ProductDetailAsyncTask extends
            AsyncTask<Void, Void, String> {
        @Override
        protected void onPreExecute() {
            Logger.d(TAG, "ProductDetailAsyncTask onPreExecute");
            // showWaitingDialog();
            showLoadingLayout(null);
        }

        @Override
        protected String doInBackground(Void... params) {
            Logger.i(TAG, "Start to get Product Data!");
            // 获取商品详情
            String currencyCode = StringUtil.getConfig(
                    ServerConstant.Parameter.PARAMETER_NAME_CURRENCYCODE,
                    getString(R.string.currency_default_currencyCode));
            try {
                newProductModel = productServiceProvider.getProductDetail(
                        productId, currencyCode);
            } catch (DxException e) {
                return e.getErrCode();
            }
            return "0";
        }

        @Override
        protected void onPostExecute(String result) {
            Logger.d(TAG, "ProductDetailAsyncTask onPostExecute");
            hideAllLayout();
            if ("0".equals(result)) {
                // 获得商品详情，成功后获得评论数量
                if (null == newProductModel) {

                } else {
                    if (newProductModel.getWarehouses() == ProductModel.WarehouseTag.US){
                        //是US仓
                        isUS = true;
                    }

                    cartLayout.setVisibility(View.VISIBLE);
                    // 判断是否有详情页显示继续拖动提示文本
                    if (!TextUtils.isEmpty(newProductModel.getIntroduction())
                            || !TextUtils.isEmpty(newProductModel.getSpec())) {
                        descriptionKeepPushText.setVisibility(View.VISIBLE);
                    } else {
                        descriptionKeepPushText.setVisibility(View.GONE);
                    }
                    if (!isFinishing()) {
                        // 先设置评论数量
                        reviewsCount.setText(getString(
                                R.string.detail_reviews_count,
                                newProductModel.getReviewCount()));
                        fillDataForView(newProductModel);
                        // new CommentsListAsyncTask().execute();
                        AsyncTaskUtil.executeTask(new CommentsListAsyncTask());
                    }
                    insertToNativeBrowseList(newProductModel);
                    // 记录用户浏览的商品的名称、SKU、单价
                    measureImpression();
                    // 将商品信息添加到百分点推荐
                    // addProduct2Bfd();
                    countryDialog();
                }
            } else {
                AlertToast.alert(DetailActivity.this,
                        ServerConstant.ReturnCode.MESSAGEMAP.get(result));

            }
        }
    }

    private void countryDialog() {

        if (isUS) {
            new GetCountryCodeTask(new CustomAsyncTaskListener<String>() {
                @Override
                public void onPostExecute(String s) {
                    //因为服务器返回的国家是带有引号的，比如说 "US"，需要手动去掉双引号
                    if (!"US".equals(s.replaceAll("\"", ""))) {
                        //是美国仓的商品，但是IP地址不是美国,则不能让用户点击加入购物车和购买，同时弹出对话框
                        checkUSSKU();
                    }
                }
            }).execute();
        }
    }

    private void queryCartCount() {
        // ---------修改加入是否登陆判断----------
        // int cartCount = ProviderFactory.createMyCartServiceDBProvider()
        // .getCartTotal(this);
        // if (cartCount > 0) {
        // topbarRightCart.setText(cartCount + "");
        // }
        int cartCount;
        if (!ActivityUtil.isLogin(this)) {
            // 没有登陆显示本地购物车中的产品数量
            cartCount = ProviderFactory.createMyCartServiceDBProvider()
                    .getCartTotal(this);
            if (cartCount > 0) {
                topbarRightCart.setText(cartCount + "");
                topBarRightCartLayout
                        .setBackgroundResource(R.drawable.nav_cart_new_black);
            } else {
                topBarRightCartLayout
                        .setBackgroundResource(R.drawable.nav_cart_no_black);
            }
        } else {
            // 已经登陆显示服务端购物车产品数量
            AsyncTaskUtil.executeTask(new QueryCount());
        }
    }

    /**
     * 将商品信息添加到百分点推荐
     */
    public void addProduct2Bfd() {
        Map<String, Object> params = new HashMap<String, Object>();
        URL img = null;
        URL simg = null;
        URL url = null;
        try {
            simg = new URL(newProductModel.getSmallPictureURL()[0]);
        } catch (MalformedURLException e) {
            simg = null;
        }
        try {
            img = new URL(newProductModel.getBigPictureURL()[0]);
        } catch (MalformedURLException e) {
            img = null;
        }
        try {
            url = new URL(newProductModel.getWebUrl());
        } catch (MalformedURLException e) {
            url = null;
        }
        if (simg != null) {
            params.put(ServerConstant.Bfd.BFD_SIMG, simg);
        }
        if (img != null) {
            params.put(ServerConstant.Bfd.BFD_IMG, img);
        }
        if (url != null) {
            params.put(ServerConstant.Bfd.BFD_URL, url);
        }
        params.put(ServerConstant.Bfd.BFD_NAME,
                newProductModel.getShortHeadLine1());

        BfdAgent.onAddItem(getApplicationContext(), newProductModel.getSku()
                + "", params);
    }

    /**
     * @author tony 查询线上购物车中产品品类数量
     */
    class QueryCount extends BaseNeedReLoginTask {

        int count;// 记录品类数量

        @Override
        protected String doInBackground(Void... params) {
            try {
                count = ProviderFactory.createShoppingCartServiceProvider()
                        .getCartCount(Long.parseLong(getCustomerID()),
                                ActivityUtil.getCustomerToken());
            } catch (DxException e) {
                return e.getErrCode();
            }
            return "0";
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            if (!isFinishing()) {
                if ("0".equals(result)) {
                    if (count > 0) {
                        topbarRightCart.setText(count + "");
                        topBarRightCartLayout
                                .setBackgroundResource(R.drawable.nav_cart_new_black);
                    } else {
                        topBarRightCartLayout
                                .setBackgroundResource(R.drawable.nav_cart_no_black);
                    }
                } else if (!isRelogin) {
                    AlertToast.alert(DetailActivity.this, ServerConstant.ReturnCode.MESSAGEMAP.get(result));
                }
            }
        }

        @Override
        protected Context setContext() {
            return DetailActivity.this;
        }

        @Override
        protected BaseNeedReLoginTask setTask() {
            return new QueryCount();
        }
    }

    /**
     * 加载商品评论列表任务
     *
     * @author hjd008
     * @version [版本号, 2014-12-23]
     * @see [相关类/方法]
     * @since [产品/模块版本]
     */
    private int pageIndex = 1;

    private EventBuilder eventBuilder;

    private TextView addToCartBtn;

    private TextView buyNowBtn;

    private Button soldOutBtn;

    private LinearLayout buyNowAddLayout;

    private PagerSlidingTabStrip pagerSlidingTabStrip;

    private PagerSlidingTabStrip topPagerSlidingTabStrip;

    private MyViewPager viewPager;

    private ProductDetailDescriptionViewPagerAdapter viewPagerAdapter;

    private Intent intentFrom;

    private boolean isFromMessage;

    private RelativeLayout invalidActiveLayout;

    private String noticeID;

    private boolean needCheckValid;

    protected class CommentsListAsyncTask extends BaseNeedReLoginTask {
        @Override
        protected void onPreExecute() {
            Logger.d(TAG, "CommentsListAsyncTask onPreExecute");
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(Void... params) {
            Logger.d(TAG, "CommentsListAsyncTask doInBackground");
            try {
                onePageReviewList = productServiceProvider
                        .getCusotmerReviewList(productId, "", "", pageIndex, 2,
                                ActivityUtil.getCustomerToken());
            } catch (DxException e) {
                return e.getErrCode();
            } catch (Exception e) {
                Logger.e("DetailActivity", "CommentsListAsyncTask", e);
            }
            return "0";
        }

        @Override
        protected void onPostExecute(String result) {
            Logger.d(TAG, "CommentsListAsyncTask onPostExecute");
            super.onPostExecute(result);
            if (!isFinishing()) {
                if ("0".equals(result)) {
                    if (null != onePageReviewList
                            && !onePageReviewList.isEmpty()) {
                        // 评论数量
                        int newReviewCount = onePageReviewList.size();
                        // 评论数大于1,显示Reviews(X),否则显示Review(X)(X为评论数量)
                        if (newReviewCount >= 1) {
                            detailReviews.setVisibility(View.VISIBLE);
                            if (null != newProductModel) {
                                reviewsCount.setText(getString(
                                        R.string.detail_reviews_count,
                                        newProductModel.getReviewCount()));
                            }
                            if (newReviewCount == 1) {
                                seeMore.setVisibility(View.GONE);
                            }
                        } else {
                            detailReviews.setVisibility(View.GONE);
                        }
                        if (newReviewCount > 0) {
                            // 商品评论人昵称和时间
                            reviewName.setText(onePageReviewList.get(0)
                                    .getSubject());
                            SimpleDateFormat data1 = new SimpleDateFormat(
                                    "MM/dd/yyy HH:SS");
                            SimpleDateFormat data = new SimpleDateFormat(
                                    "yyyy-MM-dd HH:SS");
                            String dataStr = onePageReviewList.get(0)
                                    .getTimestamp();
                            try {
                                Date nowDate = data1.parse(dataStr);
                                dataStr = data.format(nowDate);
                            } catch (ParseException e) {
                                dataStr = onePageReviewList.get(0)
                                        .getTimestamp();
                            } finally {
                                reviewCustomer
                                        .setText(getString(
                                                R.string.detail_reviews_time,
                                                new Object[]{
                                                        onePageReviewList
                                                                .get(0)
                                                                .getUsername(),
                                                        dataStr}));
                            }
                            reviewDescription.setText(onePageReviewList.get(0)
                                    .getContent());
                        }
                    }
                } else if (!isRelogin) {
                    // //评论页面显示 无数据
                    // AlertToast.alert(DetailActivity.this,
                    // ServerConstant.ReturnCode.MESSAGEMAP.get(result));
                }
            }
        }

        @Override
        protected Context setContext() {
            return DetailActivity.this;
        }

        @Override
        protected BaseNeedReLoginTask setTask() {
            return new CommentsListAsyncTask();
        }
    }

    /**
     * 添加到购物车任务
     *
     * @author hjd008
     * @version [版本号, 2014-12-23]
     * @see [相关类/方法]
     * @since [产品/模块版本]
     */
    protected class AddToWishListAsyncTask extends
            BaseNeedReLoginTask {

        private final int sku;

        private final String source;

        String userName;

        public AddToWishListAsyncTask(int sku, String source) {
            this.sku = sku;
            this.source = source;
        }

        @Override
        protected void onPreExecute() {
            // showWaitingDialog();
            showLoadingLayout(null);
        }

        @Override
        protected String doInBackground(Void... params) {
            try {
                userName = StringUtil.getConfig(DetailActivity.this,
                        ServerConstant.Parameter.PARAMETER_NAME_USER_ACCOUNT);
                ProviderFactory.createUserServiceProvider().addWishlistForUser(
                        sku, source, ActivityUtil.getCustomerID(),
                        ActivityUtil.getCustomerToken());
            } catch (DxException e) {
                return e.getErrCode();
            } catch (Exception e) {
                Logger.e("MyCartActivity", "AddToWishListAsyncTask", e);
            }
            return "0";
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            if (!isFinishing()) {
                // hideWaitingDialog();
                hideAllLayout();
                isActionCompleted = true;
            }
            if ("0".equals(result)) {
                // 集成GA
                eventBuilder.setCategory("Click").setAction(
                        "Add sku:" + sku + " to wish list");
                t.send(eventBuilder.build());
                if (!isFinishing()) {
                    AlertToast.alert(DetailActivity.this,
                            R.string.user_collection_add_success);
                    farvitorBtn.setImageResource(R.drawable.like_orange);
                }
                StringUtil.saveConfig(sku + "", userName);
                GlobalConfig.getInstance().setShoppingCartChange(true);
            } else if (!isRelogin) {
                if (User.WISHLIST_ADD_ERROR.equals(result)) {
                    if (!isFinishing()) {
                        farvitorBtn.setImageResource(R.drawable.like_orange);
                    }
                    StringUtil.saveConfig(sku + "", userName);
                }
                if (!isFinishing()) {
                    AlertToast.alert(DetailActivity.this,
                            ServerConstant.ReturnCode.MESSAGEMAP.get(result));
                }
            }
        }

        @Override
        protected Context setContext() {
            return DetailActivity.this;
        }

        @Override
        protected BaseNeedReLoginTask setTask() {
            return new AddToWishListAsyncTask(sku, source);
        }
    }

    /**
     * 衡量展示 要衡量产品展示，请构建Product对象，并使用addImpression方法随匹配发送此对象。 改造，用来记录浏览历史（GA）
     *
     * @see [类、类#方法、类#成员]
     */
    private void measureImpression() {
        Product product = new Product()
                .setId(String.valueOf(newProductModel.getSku()))
                .setName(newProductModel.getShortHeadLine1())
                .setVariant(newProductModel.getSpec())
                .setPrice(newProductModel.getPrice());

        ProductAction productAction = new ProductAction(
                ProductAction.ACTION_DETAIL);
        // HitBuilders.ScreenViewBuilder builder = new
        // HitBuilders.ScreenViewBuilder()
        // .addImpression(product, "Browse Details");
        HitBuilders.ScreenViewBuilder builder = new HitBuilders.ScreenViewBuilder()
                .addProduct(product).setProductAction(productAction);

        // Tracker t = DXApplication.getContext().getTracker(
        // TrackerName.APP_TRACKER);
        // t.setScreenName(DetailActivity.class.getSimpleName());
        t.send(builder.build());
    }

    /**
     * 衡量添加到购物车
     *
     * @see [类、类#方法、类#成员]
     */
    private void measureAddToCart() {
        Product product = new Product()
                .setId(String.valueOf(newProductModel.getSku()))
                .setName(newProductModel.getShortHeadLine1())
                .setVariant(newProductModel.getSpec())
                .setPrice(newProductModel.getPrice());
        // ProductAction productAction = new ProductAction(
        // ProductAction.ACTION_CLICK).setProductActionList("Add To Cart");
        ProductAction productAction = new ProductAction(
                ProductAction.ACTION_ADD);
        HitBuilders.ScreenViewBuilder builder = new HitBuilders.ScreenViewBuilder()
                .addProduct(product).setProductAction(productAction);

        // Tracker t = DXApplication.getContext().getTracker(
        // TrackerName.APP_TRACKER);
        // t.setScreenName(DetailActivity.class.getSimpleName());
        t.setScreenName("ProductDetail");
        t.send(builder.build());
    }

    @Override
    protected void onDestroy() {
        hideWaitingDialog();
        super.onDestroy();

    }

    /**
     * 检查库存是否不足
     *
     * @param orderProductModelresults
     * @return
     */
    private boolean checkLimit(
            ArrayList<OrderProductModel> orderProductModelresults) {
        if (null != orderProductModelresults) {
            OrderProductModel productModel = orderProductModelresults.get(0);
            SalesLimit salesLimit = productModel.getSalesLimit();
            if (salesLimit != null && salesLimit.getDistributionPolicy() == 0) {
                return false;
            }
        } else {
            return false;
        }
        return true;
    }

    /**
     * buyNow跳转逻辑
     *
     * @param isLogin
     * @param orderProductModelresults
     * @param previewOrder
     */
    private void buyNow(boolean isLogin,
                        ArrayList<OrderProductModel> orderProductModelresults,
                        PreviewOrderModel previewOrder) {
        Intent intent = new Intent();
        if (isLogin) {
            intent.setClass(this, OrderPlaceActivity.class);
        } else {
            intent.setClass(this, LoginActivity.class);

        }
        if (null != orderProductModelresults
                && !orderProductModelresults.isEmpty()) {
            intent.putExtra(
                    ServerConstant.Parameter.PARAMETER_NAME_LOGIN_ACTION_TYPE,
                    ServerConstant.Parameter.PARAMETER_ACTION_TYPE_PRODUCT_DETIAL);
            // 登陆成功后直接跳转到checkout页面所需要的数据
            intent.putParcelableArrayListExtra(
                    ServerConstant.Parameter.PARAMETER_NAME_ORDER_ORDERMAP,
                    orderProductModelresults);
            intent.putExtra("isClearCart", false);
            if (previewOrder != null) {
                if (!TextUtils.isEmpty(previewOrder.getCurrencyCodeStr())) {
                    intent.putExtra(
                            ServerConstant.Parameters.PARAMETERS_CURRENCYCODESTR,
                            previewOrder.getCurrencyCodeStr());
                }
                intent.putExtra(ServerConstant.Parameters.PARAMETERS_DISCOUNT,
                        previewOrder.getAllDiscountTotal());
                intent.putExtra(
                        ServerConstant.Parameters.PARAMETERS_GRANDTOTAL,
                        previewOrder.getGrandTotal());
                intent.putExtra(ServerConstant.Parameters.PARAMETERS_SUBTOTAL,
                        previewOrder.getGoodsTotal());
                intent.putExtra(ServerConstant.Parameters.PARAMETERS_RETURNSC,
                        previewOrder.getExpectReturnSCAmount());

            }
            startActivity(intent);
        }
    }

    /**
     * 点击Buy后校验库存
     *
     * @author Administrator
     */
    class CheckStock extends BaseNeedReLoginTask {

        private PreviewOrderModel previewOrder;

        @Override
        protected void onPreExecute() {
            showLoadingLayout(null);
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(Void... arg0) {
            ArrayList<Lines> lines = new ArrayList<Lines>();
            Lines line = new Lines();
            line.setSku(newProductModel.getSku());
            line.setQty(1);
            line.setSellingPrice(newProductModel.getPrice());
            lines.add(line);
            try {
                previewOrder = ProviderFactory.createCouponServiceProvider()
                        .PreviewOrder(Integer.parseInt(getCustomerID()), null,
                                0, lines, null, "USD",
                                ActivityUtil.getCustomerToken(), null);
            } catch (DxException e) {
                return e.getErrCode();
            }
            return "0";
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            ArrayList<OrderProductModel> orderProductModelresults = new ArrayList<OrderProductModel>();
            hideAllLayout(null);
            if ("0".equals(result)) {
                if (previewOrder != null && previewOrder.getLines() != null) {
                    orderProductModelresults.clear();
                    orderProductModelresults.addAll(previewOrder.getLines());
                    if (checkLimit(orderProductModelresults)) {
                        // 判断是否登录
                        boolean isLogin = ActivityUtil
                                .isLogin(DetailActivity.this);
                        buyNow(isLogin, orderProductModelresults, previewOrder);
                    } else {
                        AlertToast.alert(DetailActivity.this,
                                R.string.goods_sold_out);
                    }
                }
            } else if (!isRelogin) {
                // 加载失败
                AlertToast.alert(DetailActivity.this,
                        ServerConstant.ReturnCode.MESSAGEMAP.get(result));
            }
        }

        @Override
        protected Context setContext() {
            return DetailActivity.this;
        }

        @Override
        protected BaseNeedReLoginTask setTask() {
            return new CheckStock();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (isFromMessage) {
                backToHome();
            } else {
                finish();
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    private void initWebView(final WebView webView, final String html) {
        final WebSettings settings = webView.getSettings();
        settings.setJavaScriptEnabled(true);
        // 设置出现缩放工具
        settings.setDisplayZoomControls(false);
        settings.setBuiltInZoomControls(true);
        settings.setSupportZoom(true);
//		settings.setDomStorageEnabled(true);
        //自适应屏幕
        settings.setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);
        settings.setUseWideViewPort(true);
        settings.setLoadWithOverviewMode(true);

        webView.setWebViewClient(new WebViewClient() {
            // 跳过HTTPS验证
            @Override
            public void onReceivedSslError(WebView view,
                                           SslErrorHandler handler, SslError error) {
                if (com.weipu.common.util.GlobalConfig.getInstance().isCheckSSL()) {
                    handler.proceed();
                } else {
                    handler.cancel();
                }
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }
        });
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ECLAIR_MR1) {
            new Object() {
                public void setLoadWithOverviewMode(boolean overview) {
                    settings.setLoadWithOverviewMode(overview);
                }
            }.setLoadWithOverviewMode(true);
        }

        settings.setCacheMode(WebSettings.LOAD_DEFAULT);

        getWindow().getDecorView().post(new Runnable() {
            @Override
            public void run() {
                // webView.loadUrl("http://www.baidu.com");
                if (!TextUtils.isEmpty(html)) {
                    webView.loadDataWithBaseURL(null, html, "text/html",
                            "utf-8", null);
                }
            }
        });
    }

    @Override
    public void scrollChanged() {
        // BottomView Y轴上滚动的举例
        int scrollY = container.getBottomViewScroolY();
        // 控制topPagerSlidingTabStrip显示与隐藏
        if (scrollY > 0) {
            topPagerSlidingTabStrip.setVisibility(View.VISIBLE);
            pagerSlidingTabStrip.setVisibility(View.INVISIBLE);
        } else {
            topPagerSlidingTabStrip.setVisibility(View.GONE);
            pagerSlidingTabStrip.setVisibility(View.VISIBLE);
        }
    }

    // @JavascriptInterface
    // public void resize(final float height) {
    // DetailActivity.this.runOnUiThread(new Runnable() {
    // @Override
    // public void run() {
    // webView.setLayoutParams(new
    // LinearLayout.LayoutParams(getResources().getDisplayMetrics().widthPixels,
    // (int) (height * getResources().getDisplayMetrics().density)));
    // }
    // });
    // }
}